package com.book.service.impl;

import com.book.dao.BookDao;
import com.book.dao.ShopDetailDao;
import com.book.dto.ShopDetailDto;
import com.book.helper.ShopCarDetailHelper;
import com.book.pojo.Book;
import com.book.pojo.ShopDetail;
import com.book.service.ShopCarDetailService;
import com.google.common.collect.Lists;
import org.apache.commons.collections.CollectionUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.util.StringUtils;

import java.util.List;
import java.util.stream.Collectors;

/**
 * @Author 李锦程
 * @Date 2021/3/9 2:13 下午
 * @Package com.book.service.impl
 * @Version 1.0
 */
@Service
public class ShopCarDetailServiceImpl implements ShopCarDetailService {
    @Autowired
    private ShopDetailDao shopDetailDao;
    @Autowired
    private BookDao uBookDao;

    @Override
    public List<ShopDetailDto> getShopCarDetail(String scCode) {
        if (StringUtils.isEmpty(scCode)){
            return Lists.newArrayList();
        }
        List<ShopDetail> userShopCarDetail = shopDetailDao.getUserShopCarDetail(scCode);
        return userShopCarDetail.stream().map(ShopCarDetailHelper::covertPoDto).collect(Collectors.toList());
    }

    @Override
    public Integer save(ShopDetailDto shopDetailDto) {
        ShopDetail sd = ShopCarDetailHelper.covertDtoPo(shopDetailDto);
        return shopDetailDao.insertSelective(sd);
    }

    @Override
    public void updateCarBookNum(Integer id, int num) {
        ShopDetail shopDetail = shopDetailDao.selectByPrimaryKey(id);
        Book uBookByCode = uBookDao.getUBookByCode(shopDetail.getUbCode());
        Double price = shopDetail.getPrice()+num * uBookByCode.getBookPrice();
        shopDetailDao.updateCarBookNum(id,num,price);
    }

    @Override
    public Integer deleteCarBook(Integer id) {
        return shopDetailDao.deleteByPrimaryKey(id);
    }

    @Override
    public ShopDetail getShopCarBook(int parseInt) {
        return shopDetailDao.selectByPrimaryKey(parseInt);
    }

    @Override
    public List<ShopDetailDto> getShopCarDetail(List<Integer> ids) {
        List<ShopDetail> shopCarDetail = shopDetailDao.getShopCarDetail(ids);
        return CollectionUtils.isEmpty(shopCarDetail)?Lists.newArrayList():shopCarDetail.stream().map(ShopCarDetailHelper::covertPoDto).collect(Collectors.toList());
    }
}
